//
//  TYPageControl.m
//  Somago
//
//  Created by 谢航宇_WORK on 2021/12/29.
//  Copyright © 2021 juniu. All rights reserved.
//

#import "TYPageControl.h"

@implementation TYPageControl

- (instancetype)init {
    self = [super init];
    if (self) {
        self.userInteractionEnabled = NO;
    }
    return self;
}

- (void)setNumberOfPages:(NSInteger)numberOfPages {
    if (_numberOfPages == numberOfPages) {
        return;
    }
    _numberOfPages = numberOfPages; 
    __weak typeof(self) weakSelf = self;
    CGFloat space = 4;
    CGFloat nomalWidth = 4 ;
    CGFloat selectWidth = 8.5;
    CGFloat allWidth = (space + nomalWidth) * (numberOfPages - 1) + selectWidth;
    UIImageView * lastImageView = nil;
    for (int i = 0; i < _numberOfPages; i ++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.layer.cornerRadius = 2 ;
        imageView.clipsToBounds = YES;
        [self addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            if (lastImageView) {
                make.left.mas_equalTo(lastImageView.mas_right).offset(space);
            }else {
                make.left.mas_equalTo(weakSelf.mas_centerX).offset(-allWidth/2.0);
            }
            make.centerY.mas_equalTo(weakSelf);
            make.width.mas_equalTo(nomalWidth);
            make.height.mas_equalTo(4);
        }];
        lastImageView = imageView;
    }
}

- (void)setCurrentPage:(NSInteger)currentPage {
    _currentPage = currentPage;
    CGFloat nomalWidth = 4;
    CGFloat selectWidth = 8.5;
    for (NSInteger subviewIndex = 0; subviewIndex < [self.subviews count]; subviewIndex ++) {
        UIImageView *subview = [self.subviews objectAtIndex:subviewIndex];
        if (subviewIndex == currentPage) {
            subview.backgroundColor = [UIColor blackColor];
            [subview mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(selectWidth);
            }];
        } else {
            subview.backgroundColor = [UIColor grayColor];
            [subview mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(nomalWidth);
            }];
        }
    }
}
 


@end
